<template>
  <el-upload
    :data = "dataObj"
    :multiple="multiple"
    :headers="headers"
    :on-success="handleImageSuccess"
    :http-request="handleUploadRequest"
    :action="action"
    :accept="accept"
    :on-remove="handleRemove"
    :file-list="fileList"
    :limit="1">
    <el-button size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>

<script>

import chunk from './chunk'
import { getToken } from '@/utils/auth'

export default {
  name: 'SingleImageUpload',
  props: {
    value: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '*'
    },
    multiple: {
      type: Boolean,
      default: false
    },
      imagelist: {
          type: Array,
          default: () => {
              return [];
          }
      }
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + '/upload/chunk',
      dataObj: {},
      percentage: 0,
      headers: {
        'X-Token': getToken()
      },
        fileList: this.imagelist ? this.imagelist : [],
      tmp: ''
    }
  },
  watch: {
      fileList: function(fileList, oldFileList) {
          let id = ''
          if (fileList.length > 0) {
              for (const item of fileList) {
                  // console.log(item)
                  if (item.response) {
                      id = item.response.data.id
                  } else if (item.id) {
                      id = item.id
                  }
              }
          }
          this.emitInput(id)
      },
      imagelist: function(newFileList, oldFileList){
          this.fileList = newFileList
      }
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = []
    },
    handleUploadRequest(options) {
      chunk(options)
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    handleImageSuccess(response, file, fileList) {
      this.fileList = fileList
    },
    handleUploadProgress(event, file, fileList) {
      // console.log(event)
      // if (event.percent) {
      //   this.percentage = event.percent
      // }
      // console.log(event, file, fileList)
    },
    beforeUpload() {
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.image {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
